<template>
 <form class="validate-form-container">
    <slot name="default"></slot>
    <div class="submit-area" @click.prevent="formSubmit" >
      <slot name="submit">
        <button type="button"  class="btn btn-primary shadow">提交</button>
      </slot>
    </div>
  </form>
</template>

<script lang='ts'>
import { defineComponent, onMounted, onUnmounted } from 'vue'
import mitt from 'mitt'
export const emitter = mitt()
type ValidateFunc=() => boolean
export default defineComponent({
  name: 'ValidateForm',
  emits: ['form-submit'],
  setup (props, context) {
    let FuncArray: ValidateFunc[] = []
    const formSubmit = () => {
      const results = FuncArray.map(func => func()).every(result => result)
      // 一点击就开始循环的验证里的每一项验证函数返回值，只要一个错误了，直接就提前返回了
      context.emit('form-submit', results)
    }
    const callback = (func?: ValidateFunc) => {
      if (func) {
        FuncArray.push(func)
      }
    }// 这里的func就是子组件发送来的验证函数。不断的放到这个array里。
    emitter.on('item', callback)
    onUnmounted(() => {
      emitter.off('item', callback)
      FuncArray = []
    })
    return {
      formSubmit
    }
  }

})
</script>

<style>

</style>
